package com.gzdh.dishrecognition.util;

import android.os.Environment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class SdcardUtils {

    private static final String DEVICE_ID_BK = Environment.getExternalStorageDirectory() + "/com.chelmey.android.dishidf/DEVICE_ID_BK";

    public static String getRegistrationNumber() {
        try {
            String registInfo = SdcardUtils.getDeviceIDFromBackFile();
            if (registInfo == null) return null;
            JSONObject jsonObject = JSON.parseObject(registInfo);
            return jsonObject.getString("deviceId");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getDeviceIDFromBackFile() {
        File bkFile = new File(DEVICE_ID_BK);
        if (bkFile.exists()) {
            try {
                BufferedReader bufferedReader = new BufferedReader(new FileReader(bkFile));
                String deviceId = bufferedReader.readLine();
                bufferedReader.close();
                if (deviceId != null) {
                    return deviceId;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static boolean saveDeviceIDToBackFile(String deviceId) {
        File bkFile = new File(DEVICE_ID_BK);
        if (!bkFile.getParentFile().exists()) {
            bkFile.getParentFile().mkdirs();
        }
        try {
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(bkFile));
            bufferedWriter.write(deviceId);
            bufferedWriter.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
